import { z } from 'zod';

const statusEnum = z.enum(['active', 'inactive', 'banned']);

export function getUserFormSchema(mode = 'create') {
  const baseSchema = {
    email: z
      .string({ required_error: '邮箱为必填项' })
      .email('请输入有效的邮箱地址')
      .max(255, '邮箱长度不能超过255个字符'),
    username: z
      .string({ required_error: '用户名为必填项' })
      .min(2, '用户名至少需要2个字符')
      .max(100, '用户名长度不能超过100个字符'),
    fullName: z
      .string()
      .max(255, '姓名长度不能超过255个字符')
      .optional()
      .or(z.literal('')),
    phone: z
      .string()
      .max(20, '手机号长度不能超过20个字符')
      .optional()
      .or(z.literal('')),
    avatarUrl: z
      .string()
      .url('请输入有效的头像URL')
      .optional()
      .or(z.literal('')),
    bio: z
      .string()
      .max(2000, '个人简介长度不能超过2000个字符')
      .optional()
      .or(z.literal('')),
    roleId: z
      .string({ required_error: '请选择角色' })
      .regex(/^\d+$/, '角色ID必须为数字'),
    status: statusEnum.default('active'),
    emailVerified: z.boolean().default(false),
  };

  if (mode === 'create') {
    return z
      .object({
        ...baseSchema,
        password: z
          .string({ required_error: '密码为必填项' })
          .min(6, '密码至少需要6个字符')
          .max(255, '密码长度不能超过255个字符'),
        confirmPassword: z
          .string({ required_error: '请确认密码' })
          .min(6, '确认密码至少需要6个字符'),
      })
      .refine((data) => data.password === data.confirmPassword, {
        message: '两次密码输入不一致',
        path: ['confirmPassword'],
      });
  }

  return z
    .object({
      ...baseSchema,
      password: z
        .string()
        .min(6, '密码至少需要6个字符')
        .max(255, '密码长度不能超过255个字符')
        .optional()
        .or(z.literal('')),
      confirmPassword: z
        .string()
        .min(6, '确认密码至少需要6个字符')
        .optional()
        .or(z.literal('')),
    })
    .superRefine((data, ctx) => {
      if (data.password && !data.confirmPassword) {
        ctx.addIssue({
          path: ['confirmPassword'],
          code: z.ZodIssueCode.custom,
          message: '请再次输入密码以确认',
        });
      }
      if (data.password && data.confirmPassword) {
        if (data.password !== data.confirmPassword) {
          ctx.addIssue({
            path: ['confirmPassword'],
            code: z.ZodIssueCode.custom,
            message: '两次密码输入不一致',
          });
        }
      }
    });
}

export const STATUS_OPTIONS = [
  { label: '启用', value: 'active' },
  { label: '禁用', value: 'inactive' },
  { label: '封禁', value: 'banned' },
];


